﻿using BaseUI;
using BLL;
using Model;
using System;
using System.Data;
using System.Web.UI.WebControls;

namespace Thksoft.BusinessExpansion.Templete
{
    public partial class Authority : BasePage
    {
        private Sys_RoleBLL srb = new Sys_RoleBLL();
        private Sys_ModuleBLL smb = new Sys_ModuleBLL();
        private Sys_RoleModuleBLL srmb = new Sys_RoleModuleBLL();
        private static DataTable dtRoleModul = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataTable dtmg = new DataTable();
                dtmg.Columns.Add("ID", Type.GetType("System.String"));
                dtmg.Columns.Add("NAME", Type.GetType("System.String"));

                Qs_Base_Set model = new Qs_Base_SetBLL().GetModelByName("选项卡");
                string[] Card = model.Set_value.Split(';');
                for (int c = 0; c < Card.Length; c++)
                {
                    DataRow newRow = dtmg.NewRow();
                    newRow["ID"] = Card[c].Split(',')[0];
                    newRow["NAME"] = Card[c].Split(',')[1];
                    dtmg.Rows.Add(newRow);
                }

                Session["ModuleGroup"] = dtmg;
                Bind();
            }
            if (stutar.Value == "Select")
            {
                bindRole();
                stutar.Value = "";
            }
            if (stutar.Value == "showTree")
            {
                bindTree();
                stutar.Value = "";
            }
            if (stutar.Value == "Preservation")
            {
                Add();
                stutar.Value = "";
            }
            DivSelectUser.Text = stutar3.Value;

            TreeView1.Attributes.Add("onclick", "postBackByObject()");

            if (lognUser.USER_ID != 1)
            {
                //btnGroup.Visible = false;
            }
        }

        #region 加载绑定

        private void Bind()
        {
            DataTable dt = srb.GetAllInfo();

            if (dt == null || dt.Rows.Count == 0)
            {
                return;
            }
            string str = "";
            str += "<table width='100%' border='0' cellspacing='0' cellpadding='0' style='margin-top:5px;'>";
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                str += "<tr>";
                str += "<td onmouseover='mover(" + i + ")' onmouseout='mout(" + i + ")'; id='td" + i + "'><div ondblclick='showTree(" + dt.Rows[i]["ROLE_ID"] + ")' style='cursor:pointer;padding-top:2px;padding-left:2px'> " + dt.Rows[i]["ROLE_NAME"].ToString() + "</div> </td>";
                str += "</tr>";
            }
            str += "</table>";
            Label1.Text = str;
        }

        #endregion 加载绑定

        #region 绑定树形菜单

        private void bindTree()
        {
            TreeView1.Nodes.Clear();
            DataTable dtModule = smb.GetAllInfo1();
            dtRoleModul = srmb.findByRole(stutar2.Value.Trim());
            TreeNode node = null;

            try
            {
                DataTable dtmg = (DataTable)Session["ModuleGroup"];
                //if (dtmg.AsEnumerable().Where(a=>a["ID"].ToString()=="-1").Count()==0)
                //{
                //    var row = dtmg.NewRow();
                //    row["ID"] = "-1";
                //    row["NAME"] = "主菜单";
                //    dtmg.Rows.Add(row);
                //}
                if (dtmg.Rows.Count > 0)
                {
                    for (int g = 0; g < dtmg.Rows.Count; g++)
                    {
                        TreeNode nodegm = new TreeNode();
                        nodegm.Text = dtmg.Rows[g]["NAME"].ToString();
                        nodegm.Value = dtmg.Rows[g]["ID"].ToString();
                        TreeView1.Nodes.Add(nodegm);

                        for (int i = 0; i < dtModule.Rows.Count; i++)
                        {
                            if (dtModule.Rows[i]["MODULE_PARENTID"].ToString() == dtmg.Rows[g]["ID"].ToString())
                            {
                                node = new TreeNode();
                                node.Text = dtModule.Rows[i]["MODULE_NAME"].ToString();
                                node.Value = dtModule.Rows[i]["MODULE_ID"].ToString();

                                for (int j = 0; j < dtRoleModul.Rows.Count; j++)
                                {
                                    if (dtRoleModul.Rows[j]["MODULE_ID"].ToString() == dtModule.Rows[i]["MODULE_ID"].ToString())
                                    {
                                        if (!nodegm.Checked)
                                        {
                                            nodegm.Checked = true;
                                        }
                                        node.Checked = true;
                                    }
                                }

                                nodegm.ChildNodes.Add(node);
                                treeNode(node, Convert.ToInt32(dtModule.Rows[i]["MODULE_ID"].ToString()));
                            }
                        }

                        nodegm.Expand();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(Page, ex.Message);
            }
        }

        private void treeNode(TreeNode node, int id)
        {
            DataTable dtModule = smb.GetAllInfo2();
            TreeNode no = null;

            for (int i = 0; i < dtModule.Rows.Count; i++)
            {
                if (Convert.ToInt32(dtModule.Rows[i]["MODULE_PARENTID"].ToString()) == id)
                {
                    no = new TreeNode();
                    no.Text = dtModule.Rows[i]["MODULE_NAME"].ToString();
                    no.Value = dtModule.Rows[i]["MODULE_ID"].ToString();

                    if (dtRoleModul != null)
                    {
                        for (int j = 0; j < dtRoleModul.Rows.Count; j++)
                        {
                            if (dtRoleModul.Rows[j]["MODULE_ID"].ToString() == dtModule.Rows[i]["MODULE_ID"].ToString())
                            {
                                no.Checked = true;
                            }
                        }
                    }

                    node.ChildNodes.Add(no);

                    //treeNodeButtons(no, dtModule.Rows[i]["MODULE_ID"].ToString());
                }
            }
        }

        private void treeNodeButtons(TreeNode node, string id)
        {
            Qs_Base_Set model = new Qs_Base_SetBLL().GetModelByName("按钮队列");
            string[] buttons = model.Set_value.Split(',');
            string buttonStr = "";

            if (dtRoleModul != null)
            {
                for (int j = 0; j < dtRoleModul.Rows.Count; j++)
                {
                    //if (dtRoleModul.Rows[j]["MODULE_ID"].ToString() == id)
                    //{
                    //    buttonStr = dtRoleModul.Rows[j]["BUTTONS"].ToString();
                    //}
                }
            }

            for (int i = 0; i < buttons.Length; i++)
            {
                TreeNode no = new TreeNode();
                no.Text = buttons[i];
                no.Value = "0";

                if (buttonStr.Contains(buttons[i]))
                {
                    no.Checked = true;
                }

                node.ChildNodes.Add(no);
            }
        }

        #endregion 绑定树形菜单

        #region 查询角色

        private void bindRole()
        {
            string roName = "";
            if (RoleName.Value.ToString().Trim() == "角色名称")
            {
                roName = "";
            }
            else
            {
                roName = RoleName.Value.ToString().Trim();
            }
            DataTable dt = srb.findLikeName(roName);

            if (dt == null || dt.Rows.Count == 0)
            {
                Label1.Text = "";
                return;
            }
            string str = "";
            str += "<table width='100%' border='0' cellspacing='0' cellpadding='0' style='margin-top:5px;'>";
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                str += "<tr>";
                str += "<td onmouseover='mover(" + i + ")' id='td" + i + "' onmouseout='mout(" + i + ")';><div ondblclick='showTree(" + dt.Rows[i]["ROLE_ID"] + ")' style='cursor:pointer'  > " + dt.Rows[i]["ROLE_NAME"].ToString() + "</div> </td>";
                str += "</tr>";
            }
            str += "</table>";
            Label1.Text = str;
        }

        #endregion 查询角色

        #region 添加

        private void Add()
        {
            string ModuleId = "";

            foreach (TreeNode item in TreeView1.Nodes)
            {
                if (item.Checked == true)
                {
                    Model.Sys_RoleModule role = new Model.Sys_RoleModule();

                    role.MODULE_ID = decimal.Parse(item.Value);

                    role.ROLE_ID = decimal.Parse(stutar2.Value.Trim().ToString());

                    ModuleId += item.Value + ",";

                    new BLL.Sys_RoleModuleBLL().INSERT(role, lognUser.USER_NAME);
                }
            }

            for (int i = 0; i < TreeView1.Nodes.Count; i++)
            {
                foreach (TreeNode child in TreeView1.CheckedNodes)
                {
                    if (child.Checked == true)
                    {
                        Model.Sys_RoleModule role1 = new Model.Sys_RoleModule();

                        role1.MODULE_ID = decimal.Parse(child.Value);

                        role1.ROLE_ID = decimal.Parse(stutar2.Value.Trim().ToString());

                        ModuleId += child.Value + ",";

                        new BLL.Sys_RoleModuleBLL().INSERT(role1, lognUser.USER_NAME);
                    }
                }
            }
            if (stutar2.Value.Trim().ToString() == "")
            {
                MessageBox.Show(Page, "请选择角色");
                return;
            }

            //刷新框架代码 window.parent.location= window.parent.location;
            srmb.DELETE(stutar2.Value.ToString().Trim(), ModuleId, lognUser.USER_NAME);
            MessageBox.Show(Page, "赋权成功下次登录生效");
            ModuleId = "";
            return;
        }

        #endregion 添加

        protected void TreeView1_TreeNodeCheckChanged(object sender, TreeNodeEventArgs e)
        {
            SetChildChecked(e.Node);
            SetParentChecked(e.Node);
        }

        /// <summary>
        /// 选中父节点，其所有子节点也选中
        /// </summary>
        /// <param name="parentNode"></param>
        private void SetChildChecked(TreeNode parentNode)
        {
            if (parentNode.Checked == true)
            {
                foreach (TreeNode tn in parentNode.ChildNodes)
                {
                    tn.Checked = parentNode.Checked;
                    if (tn.ChildNodes.Count > 0)
                    {
                        SetChildChecked(tn);
                    }
                }
            }
            else
            {
                foreach (TreeNode tn in parentNode.ChildNodes)
                {
                    tn.Checked = parentNode.Checked;
                    if (tn.ChildNodes.Count > 0)
                    {
                        SetChildChecked(tn);
                    }
                }
            }
        }

        /// <summary>
        /// 选中子节点，其父节点也选中
        /// </summary>
        /// <param name="childNode"></param>
        private void SetParentChecked(TreeNode childNode)
        {
            if (childNode.Checked == true)
            {
                if (childNode.Parent != null)
                {
                    childNode.Parent.Checked = childNode.Checked;
                    SetParentChecked(childNode.Parent);
                }
            }
            else
            {
                if (childNode.Parent != null)
                {
                    if (!CheckChildAllCheck(childNode.Parent))
                    {
                        childNode.Parent.Checked = childNode.Checked;
                        SetParentChecked(childNode.Parent);
                    }
                }
            }
        }

        /// <summary>
        /// 判断当前节点的兄弟节点及其子节点有没有选中的，如果有，直接返回true
        /// 如果没有，继续递归。
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        private bool CheckChildAllCheck(TreeNode node)
        {
            bool isCheck = false;
            foreach (TreeNode childNode in node.ChildNodes)
            {
                if (childNode.Checked)
                {
                    return true;
                }
                else
                {
                    isCheck = CheckChildAllCheck(childNode);
                }
            }
            return isCheck;
        }
    }
}